<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>中国股票分析系统 - 批量分析结果</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="{{ url_for('static', filename='css/style.css') }}" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .header-section { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .card { box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); border: none; }
        .signal-badge { font-size: 0.8em; }
        .signal-buy { background-color: #28a745; }
        .signal-sell { background-color: #dc3545; }
        .signal-hold { background-color: #6c757d; }
        .analysis-btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border: none; }
        .loading { display: none; }
        .strategy-checkbox { margin-right: 10px; }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="header-section py-4 mb-4">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="mb-0"><i class="fas fa-chart-line"></i> 股票分析系统</h1>
                    <p class="mb-0 mt-2">多策略综合分析 · 批量处理 · 智能推荐</p>
                </div>
                <div class="col-md-4 text-end">
                    <button class="btn btn-light btn-lg" data-bs-toggle="modal" data-bs-target="#newAnalysisModal">
                        <i class="fas fa-play"></i> 开始新分析
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <!-- 统计卡片 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-primary">{{ recent_batches|length }}</h3>
                        <p class="mb-0">历史批次</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-success">{{ available_strategies|length }}</h3>
                        <p class="mb-0">可用策略</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-warning">
                            {% set total_stocks = recent_batches[0].total_stocks if recent_batches else 0 %}
                            {{ total_stocks }}
                        </h3>
                        <p class="mb-0">最新分析股票数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center">
                    <div class="card-body">
                        <h3 class="text-info">
                            {% if recent_batches %}
                                {{ recent_batches[0].created_at.strftime('%m-%d') }}
                            {% else %}
                                --
                            {% endif %}
                        </h3>
                        <p class="mb-0">最后更新</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 最近批次分析 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-history"></i> 最近的批量分析</h5>
            </div>
            <div class="card-body">
                {% if recent_batches %}
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>批次名称</th>
                                <th>分析时间</th>
                                <th>使用策略</th>
                                <th>股票数量</th>
                                <th>信号分布</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for batch in recent_batches %}
                            <tr>
                                <td>
                                    <strong>{{ batch.batch_name }}</strong>
                                </td>
                                <td>{{ batch.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                                <td>
                                    <small class="text-muted">
                                        {% if batch.strategy_names|length > 2 %}
                                            {{ batch.strategy_names|length }}种策略
                                        {% else %}
                                            {{ batch.strategy_names|join(', ') }}
                                        {% endif %}
                                    </small>
                                </td>
                                <td>
                                    <span class="badge bg-secondary">{{ batch.total_stocks }}</span>
                                </td>
                                <td>
                                    {% if batch.buy_signals > 0 %}
                                    <span class="badge signal-badge signal-buy">买入 {{ batch.buy_signals }}</span>
                                    {% endif %}
                                    {% if batch.sell_signals > 0 %}
                                    <span class="badge signal-badge signal-sell">卖出 {{ batch.sell_signals }}</span>
                                    {% endif %}
                                    {% if batch.hold_signals > 0 %}
                                    <span class="badge signal-badge signal-hold">观望 {{ batch.hold_signals }}</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <a href="{{ url_for('batch_details', batch_id=batch.batch_id) }}" 
                                       class="btn btn-sm btn-outline-primary">
                                        <i class="fas fa-eye"></i> 查看详情
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-chart-bar fa-3x text-muted mb-3"></i>
                    <p class="text-muted">还没有批量分析记录</p>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newAnalysisModal">
                        开始第一次分析
                    </button>
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <!-- 新分析模态框 -->
    <div class="modal fade" id="newAnalysisModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-play"></i> 开始新的批量分析</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="analysisForm">
                        <div class="mb-3">
                            <label class="form-label">分析股票数量</label>
                            <select class="form-select" name="limit">
                                <option value="20">20只股票 (快速)</option>
                                <option value="50" selected>50只股票 (推荐)</option>
                                <option value="100">100只股票 (详细)</option>
                                <option value="200">200只股票 (全面)</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">选择分析策略</label>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="selectAll" checked>
                                        <label class="form-check-label" for="selectAll">
                                            <strong>全选 (推荐)</strong>
                                        </label>
                                    </div>
                                    <hr>
                                </div>
                            </div>
                            <div class="row">
                                {% for strategy in available_strategies %}
                                <div class="col-md-6">
                                    <div class="form-check strategy-checkbox">
                                        <input class="form-check-input strategy-option" type="checkbox" 
                                               value="{{ strategy }}" id="strategy_{{ loop.index }}" checked>
                                        <label class="form-check-label" for="strategy_{{ loop.index }}">
                                            {{ strategy }}
                                        </label>
                                    </div>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <strong>提示:</strong> 多策略综合分析可以提供更可靠的投资建议。
                            预计分析时间: <span id="estimatedTime">1-2分钟</span>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn analysis-btn text-white" onclick="startAnalysis()">
                        <span class="loading">
                            <span class="spinner-border spinner-border-sm" role="status"></span>
                            分析中...
                        </span>
                        <span class="not-loading">
                            <i class="fas fa-play"></i> 开始分析
                        </span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 全选/取消全选
            const selectAllCheckbox = document.getElementById('selectAll');
            if (selectAllCheckbox) {
                selectAllCheckbox.addEventListener('change', function() {
                    const checkboxes = document.querySelectorAll('.strategy-option');
                    checkboxes.forEach(cb => cb.checked = this.checked);
                });
            }

            // 估算时间更新
            const limitSelect = document.querySelector('select[name="limit"]');
            if (limitSelect) {
                limitSelect.addEventListener('change', function() {
                    const limit = parseInt(this.value);
                    const timeSpan = document.getElementById('estimatedTime');
                    if (limit <= 20) {
                        timeSpan.textContent = '30秒-1分钟';
                    } else if (limit <= 50) {
                        timeSpan.textContent = '1-2分钟';
                    } else if (limit <= 100) {
                        timeSpan.textContent = '2-4分钟';
                    } else {
                        timeSpan.textContent = '4-8分钟';
                    }
                });
            }
        });

        // 开始分析
        function startAnalysis() {
            console.log('startAnalysis函数被调用');
            
            const form = document.getElementById('analysisForm');
            if (!form) {
                console.error('找不到表单元素');
                alert('表单初始化错误');
                return;
            }
            
            const formData = new FormData(form);
            const limit = formData.get('limit');
            const selectedStrategies = Array.from(document.querySelectorAll('.strategy-option:checked'))
                .map(cb => cb.value);
            
            console.log('选择的股票数量:', limit);
            console.log('选择的策略:', selectedStrategies);
            
            if (selectedStrategies.length === 0) {
                alert('请至少选择一个分析策略！');
                return;
            }

            // 显示加载状态
            const btn = document.querySelector('button[onclick="startAnalysis()"]');
            if (!btn) {
                console.error('找不到分析按钮');
                return;
            }
            btn.querySelector('.loading').style.display = 'inline';
            btn.querySelector('.not-loading').style.display = 'none';
            btn.disabled = true;

            // 发送请求
            fetch('/api/run_analysis', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    limit: parseInt(limit),
                    strategies: selectedStrategies
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('分析完成！即将刷新页面查看结果。');
                    window.location.reload();
                } else {
                    alert('分析失败: ' + (data.error || '未知错误'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('请求失败，请检查网络连接。');
            })
            .finally(() => {
                // 恢复按钮状态
                if (btn) {
                    btn.querySelector('.loading').style.display = 'none';
                    btn.querySelector('.not-loading').style.display = 'inline';
                    btn.disabled = false;
                }
            });
        }
    </script>
</body>
</html>